package com.sky.listeners;

import com.sky.constant.MqConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.result.MultiDelayMessage;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 衷岚
 * @version 1.0
 *
 */

/**
 * 监听处理超时订单
 */
@Component
@Slf4j
public class OrderStatusListener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.DELAY_ORDER_QUEUE,durable = "true"),
            exchange =@Exchange(name = MqConstant.DELAY_EXCHANGE,type = ExchangeTypes.TOPIC,delayed ="true" ),
            key=MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenerOrderstatus( MultiDelayMessage<Long> delayMessage){
        //1.查询订单状态
        Long orderId = delayMessage.getData();
        Orders order = orderMapper.getById(orderId);

        //2.判断订单状态

        //2.1不是未支付 返回
        if(order==null || order.getStatus()!=1){
            return;
        }

        //2.2 未支付

        //3.判断时间片是否剩余
        if(delayMessage.hasNextDelay()){
            //3.1 剩余 重发到延迟队列
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, delayMessage, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    //设置延迟发送时间
                    message.getMessageProperties().setDelay(delayMessage.removeNextDelay());
                    return message;
                }
            });
            return;
        }else{
            //3.2 时间片耗尽 --超时 自动取消订单
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason("订单超时自动取消");

            orderMapper.update(order);
            //TODO:4.改库存...


        }
    }
}
